use tauri::command;
use crate::ctp_commands::ctp::types::{ApiResponse, CtpAccountConfig};
use crate::ctp_commands::ctp::state::*;
use crate::ctp_commands::ctp::utils::{validate_login_credentials, copy_str_to_ctp_array, get_next_request_id};
use crate::logger;

// 等待登录结果（等待真实CTP回调）
fn wait_for_login_result(session_id: &str, timeout_seconds: u64) -> Result<String, String> {
    let start_time = std::time::Instant::now();
    let timeout_duration = std::time::Duration::from_secs(timeout_seconds);

    loop {
        // 检查是否超时
        if start_time.elapsed() > timeout_duration {
            return Err(format!("登录超时（{}秒），未收到CTP服务器响应。请检查：\n1. 网络连接是否正常\n2. CTP服务器地址是否正确\n3. 账户信息是否正确", timeout_seconds));
        }

        // 检查登录结果（来自Stream回调）
        {
            let login_results = get_login_results().lock().unwrap();
            if let Some((success, message)) = login_results.get(session_id) {
                if *success {
                    return Ok(message.clone());
                } else {
                    return Err(message.clone());
                }
            }
        }

        // 等待100ms后重试
        std::thread::sleep(std::time::Duration::from_millis(100));
    }
}

// 等待结算确认结果（等待真实CTP回调）
fn wait_for_settlement_confirm_result(session_id: &str, timeout_seconds: u64) -> Result<String, String> {
    println!("🔍 [DEBUG] Waiting for settlement confirm result for session_id: {}", session_id);

    let start_time = std::time::Instant::now();
    let timeout_duration = std::time::Duration::from_secs(timeout_seconds);

    loop {
        // 检查是否超时
        if start_time.elapsed() > timeout_duration {
            return Err(format!("等待结算确认结果超时 ({}秒)", timeout_seconds));
        }

        // 检查结算确认结果（来自Stream回调）
        {
            let confirm_results = get_settlement_confirm_results().lock().unwrap();
            if let Some((success, message)) = confirm_results.get(session_id) {
                if *success {
                    return Ok(message.clone());
                } else {
                    return Err(message.clone());
                }
            }
        }

        // 等待100ms后重试
        std::thread::sleep(std::time::Duration::from_millis(100));
    }
}

// 交易 API 登录命令
#[command]
pub fn trader_login(
    session_id: String,
    config: CtpAccountConfig,
) -> ApiResponse<String> {
    println!("🔍 [DEBUG] trader_login called with session_id: {}", session_id);

    // 验证登录凭据
    if let Err(validation_error) = validate_login_credentials(&config) {
        println!("❌ [ERROR] Trader login validation failed: {}", validation_error);
        return ApiResponse {
            success: false,
            data: None,
            error: Some(validation_error),
        };
    }

    // 保存会话登录信息（在验证前保存，确保wait_for_login_result能找到）
    {
        let mut session_info = get_session_login_info().lock().unwrap();
        session_info.insert(session_id.clone(), config.clone());
    }

    // 清除之前的登录结果
    {
        let mut login_results = get_login_results().lock().unwrap();
        login_results.remove(&session_id);
    }

    match std::panic::catch_unwind(|| {
        let mut apis = get_trader_apis().lock().unwrap();

        if let Some(api) = apis.get_mut(&session_id) {
            println!("✅ [DEBUG] Found Trader API for session: {}", session_id);

            // 注册前置服务器
            let trade_front = std::ffi::CString::new(config.trade_front.clone()).unwrap();
            api.register_front(trade_front);
            println!("✅ [DEBUG] Registered trade front: {}", config.trade_front);

            // 初始化API
            api.init();
            println!("✅ [DEBUG] Trader API initialized");

            // 等待连接建立
            std::thread::sleep(std::time::Duration::from_millis(2000));

            // 构造登录请求
            let mut login_req = ctp_trade_lib::CThostFtdcReqUserLoginField::default();

            // 设置字段
            copy_str_to_ctp_array(&config.broker_id, &mut login_req.BrokerID);
            copy_str_to_ctp_array(&config.account, &mut login_req.UserID);
            copy_str_to_ctp_array(&config.password, &mut login_req.Password);
            copy_str_to_ctp_array(&config.user_product_info, &mut login_req.UserProductInfo);

            println!("🔐 [DEBUG] Attempting Trader login with broker: {}, user: {}", config.broker_id, config.account);

            // 发送登录请求
            let login_result = api.req_user_login(&mut login_req, 1);

            if login_result == 0 {
                println!("✅ [DEBUG] Trader login request sent successfully, waiting for response...");

                // 等待登录结果
                match wait_for_login_result(&session_id, 15) {
                    Ok(success_msg) => {
                        // 设置登录状态
                        let mut trader_status = get_trader_login_status().lock().unwrap();
                        trader_status.insert(session_id.clone(), true);
                        
                        // 记录登录成功日志
                        logger::log_user_login(&config.account, &config.broker_id, true, None);
                        Ok(success_msg)
                    },
                    Err(error_msg) => {
                        // 记录登录失败日志
                        logger::log_user_login(&config.account, &config.broker_id, false, Some(&error_msg));
                        Err(error_msg)
                    }
                }
            } else {
                let error_msg = format!("Trader login request failed with code: {}", login_result);
                logger::log_user_login(&config.account, &config.broker_id, false, Some(&error_msg));
                Err(error_msg)
            }
        } else {
            Err(format!("Session ID {} not found", session_id))
        }
    }) {
        Ok(Ok(message)) => {
            println!("✅ [SUCCESS] {}", message);
            ApiResponse {
                success: true,
                data: Some(message),
                error: None,
            }
        },
        Ok(Err(error)) => {
            println!("❌ [ERROR] Trader login failed: {}", error);
            ApiResponse {
                success: false,
                data: None,
                error: Some(error),
            }
        },
        Err(_) => {
            let error = "Trader login panicked".to_string();
            println!("❌ [ERROR] {}", error);
            ApiResponse {
                success: false,
                data: None,
                error: Some(error),
            }
        }
    }
}

// 强制设置交易登录状态（用于调试和测试）
#[command]
pub fn force_set_trader_login_status(
    session_id: String,
    status: bool,
) -> ApiResponse<String> {
    println!("🔍 [DEBUG] force_set_trader_login_status called with session_id: {}, status: {}", session_id, status);

    let apis = get_trader_apis().lock().unwrap();
    if !apis.contains_key(&session_id) {
        return ApiResponse {
            success: false,
            data: None,
            error: Some(format!("Session ID {} not found", session_id)),
        };
    }
    drop(apis);

    let mut login_status = get_trader_login_status().lock().unwrap();
    login_status.insert(session_id.clone(), status);
    drop(login_status);

    let message = if status {
        format!("交易登录状态已设置为：已登录 (session: {})", session_id)
    } else {
        format!("交易登录状态已设置为：未登录 (session: {})", session_id)
    };

    println!("✅ [SUCCESS] {}", message);
    ApiResponse {
        success: true,
        data: Some(message),
        error: None,
    }
}

// 结算确认命令
#[command]
pub fn settlement_info_confirm(
    session_id: String,
) -> ApiResponse<String> {
    println!("📋 [DEBUG] settlement_info_confirm called with session_id: {}", session_id);

    // 检查交易API是否存在
    let trader_exists = {
        let apis = get_trader_apis().lock().unwrap();
        apis.contains_key(&session_id)
    };

    if !trader_exists {
        return ApiResponse {
            success: false,
            data: None,
            error: Some("交易API会话不存在，请先创建交易API".to_string()),
        };
    }

    // 检查是否已登录
    let login_status = {
        let login_status = get_trader_login_status().lock().unwrap();
        login_status.get(&session_id).copied().unwrap_or(false)
    };

    if !login_status {
        return ApiResponse {
            success: false,
            data: None,
            error: Some("请先完成交易登录".to_string()),
        };
    }

    // 获取登录配置信息
    let account_config = {
        let session_info = get_session_login_info().lock().unwrap();
        session_info.get(&session_id).cloned()
    };

    let account_config = match account_config {
        Some(config) => config,
        None => {
            return ApiResponse {
                success: false,
                data: None,
                error: Some("未找到登录配置信息".to_string()),
            };
        }
    };

    match std::panic::catch_unwind(|| {
        let mut apis = get_trader_apis().lock().unwrap();

        if let Some(api) = apis.get_mut(&session_id) {
            // 清除之前的结算确认结果
            {
                let mut confirm_results = get_settlement_confirm_results().lock().unwrap();
                confirm_results.remove(&session_id);
            }

            // 构造结算确认请求
            let mut settlement_confirm = ctp_trade_lib::CThostFtdcSettlementInfoConfirmField::default();

            // 设置字段
            copy_str_to_ctp_array(&account_config.broker_id, &mut settlement_confirm.BrokerID);
            copy_str_to_ctp_array(&account_config.account, &mut settlement_confirm.InvestorID);
            copy_str_to_ctp_array(&account_config.account, &mut settlement_confirm.AccountID);
            copy_str_to_ctp_array("CNY", &mut settlement_confirm.CurrencyID);

            // 获取当前日期和时间
            let now = chrono::Local::now();
            let confirm_date = now.format("%Y%m%d").to_string();
            let confirm_time = now.format("%H:%M:%S").to_string();

            copy_str_to_ctp_array(&confirm_date, &mut settlement_confirm.ConfirmDate);
            copy_str_to_ctp_array(&confirm_time, &mut settlement_confirm.ConfirmTime);

            // 获取请求ID
            let request_id = get_next_request_id();

            println!("📋 [DEBUG] Settlement confirm details:");
            println!("  - BrokerID: {}", ctp_trade_lib::gb18030_cstr_to_str_i8(&settlement_confirm.BrokerID));
            println!("  - InvestorID: {}", ctp_trade_lib::gb18030_cstr_to_str_i8(&settlement_confirm.InvestorID));
            println!("  - RequestID: {}", request_id);

            // 调用CTP API确认结算信息
            let result = api.req_settlement_info_confirm(&mut settlement_confirm, request_id);

            if result == 0 {
                println!("✅ [DEBUG] ReqSettlementInfoConfirm request sent successfully, waiting for CTP response...");

                // 等待真实的CTP响应
                match wait_for_settlement_confirm_result(&session_id, 10) {
                    Ok(success_msg) => {
                        println!("✅ [DEBUG] Settlement confirm confirmed by CTP: {}", success_msg);
                        Ok(success_msg)
                    },
                    Err(error_msg) => {
                        println!("❌ [DEBUG] Settlement confirm rejected by CTP: {}", error_msg);
                        Err(format!("CTP拒绝结算确认: {}", error_msg))
                    }
                }
            } else {
                println!("❌ [DEBUG] ReqSettlementInfoConfirm failed with code: {}", result);
                Err(format!("提交结算确认失败，错误代码: {}", result))
            }
        } else {
            Err("未找到交易API会话".to_string())
        }
    }) {
        Ok(Ok(message)) => ApiResponse {
            success: true,
            data: Some(message),
            error: None,
        },
        Ok(Err(error)) => ApiResponse {
            success: false,
            data: None,
            error: Some(error),
        },
        Err(_) => ApiResponse {
            success: false,
            data: None,
            error: Some("结算确认过程中发生异常".to_string()),
        },
    }
}

// 检查结算确认状态
#[command]
pub fn check_settlement_confirm_status(session_id: String) -> ApiResponse<bool> {
    println!("🔍 [DEBUG] check_settlement_confirm_status called with session_id: {}", session_id);

    let confirm_status = {
        let confirm_status = get_settlement_confirm_status().lock().unwrap();
        confirm_status.get(&session_id).copied().unwrap_or(false)
    };

    ApiResponse {
        success: true,
        data: Some(confirm_status),
        error: if confirm_status { None } else { Some("结算结果未确认".to_string()) },
    }
}

